package com.htfyun.ft.fragment.factory;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.htfyun.ft.BluetoothBondManager.BluetoothBondManager;
import com.htfyun.ft.BluetoothBondManager.OnBluetoothBondListener;
import com.htfyun.ft.BluetoothBondManager.OnBluetoothEnabledListener;
import com.htfyun.ft.R;
import com.htfyun.ft.utils.DebugLog;

import java.util.Set;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;

public class FragmentBluetooth_with_sink extends FactoryBaseFragment
        implements View.OnClickListener,
        OnBluetoothBondListener,
        OnBluetoothEnabledListener,
        CompoundButton.OnCheckedChangeListener{

    private TextView txtInfo;

    private SwitchCompat btSwitch;

    private Button btnSelectSystemSetting;

    private BluetoothBondManager bluetoothBondManager;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_bluetooth_with_sink;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        super.onInitView(savedInstanceState);

        txtInfo = findViewById(R.id.txtInfo);

        btnSelectSystemSetting = findViewById(R.id.btnSelectSystemSetting);
        btnSelectSystemSetting.setOnClickListener(this);

        btSwitch = (SwitchCompat) findViewById(R.id.btSwitch);
        btSwitch.setOnCheckedChangeListener(this);

        setBtnPassVisibility(View.INVISIBLE);
    }

    @Override
    protected void onVisible() {
        super.onVisible();

        initBT();
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();

        deInitBT();
    }

    private void setSwitchStatus(boolean on) {
        btSwitch.setOnCheckedChangeListener(null);
        btSwitch.setChecked(on);
        btSwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        setBluetoothEnabled(isChecked);
    }

    @Override
    public void onClick(View v) {
        if (v == btnSelectSystemSetting) {

            startBTSettings();

        }
    }

    @Override
    public void onBluetoothBonding(BluetoothDevice device) {

        String name = device.getName();
        if (TextUtils.isEmpty(name)) {
            name = device.getAddress();
        }
        String status = getString(R.string.bt_bonding_status, name);
        updateTxtInfo(status);

    }

    @Override
    public void onBluetoothBonded(BluetoothDevice device) {

        String name = device.getName();
        if (TextUtils.isEmpty(name)) {
            name = device.getAddress();
        }

        String status = getString(R.string.bt_bonded_status, name);
        updateTxtInfo(status);
        updateTxtInfo(getString(R.string.bt_sink_bond_tips));

        getHandler().sendEmptyMessageDelayed(MSG_SET_BTNPASS_VISIBLE, DELAY_SET_BTNPASS_VISIBLE);

    }

    @Override
    public void onBluetoothConnected(BluetoothDevice device, int profile) {
        onBluetoothConnected(device);
    }

    @Override
    public void onBluetoothDisconnected(BluetoothDevice device, int profile) {
        onBluetoothDisconnected(device);
    }

    @Override
    public void onBluetoothEnabled(boolean enabled) {
        setSwitchStatus(enabled);
    }


    private void initBT() {

        if (bluetoothBondManager == null) {
            bluetoothBondManager = new BluetoothBondManager(mContext);

            bluetoothBondManager.setEnabledListener(this);
            bluetoothBondManager.setBondListener(this);

            bluetoothBondManager.registerBTReceiver();
        }

    }

    private void deInitBT() {
        DebugLog.e("btOnDestroy");

        if (bluetoothBondManager != null) {

            bluetoothBondManager.unregisterBTReceiver();

            bluetoothBondManager.setEnabledListener(null);
            bluetoothBondManager.setBondListener(null);

            bluetoothBondManager.cancelDiscovery();
            bluetoothBondManager.disconnectAllProfile();

            Set<BluetoothDevice> deviceList = bluetoothBondManager.getBluetoothAdapter().getBondedDevices();

            if (deviceList != null && !deviceList.isEmpty()) {
                for (BluetoothDevice device : deviceList) {
                    bluetoothBondManager.removeBond(device);
                }
            }

            bluetoothBondManager.closeBluetooth();
            bluetoothBondManager = null;
        }
    }




    private void setBluetoothEnabled(boolean enabled) {

        if (enabled) {
            bluetoothBondManager.openBluetooth();
        } else {
            bluetoothBondManager.closeBluetooth();
        }

    }

    private void startBTSettings() {

        startAndroidBluetoothSettings();
    }

    private boolean startAndroidBluetoothSettings() {

        try {

            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
            startActivity(intent);

        } catch (Exception e) {

            return false;
        }

        return true;
    }

    private void onBluetoothConnected(BluetoothDevice device) {

        String name = device.getName();
        if (TextUtils.isEmpty(name)) {
            name = device.getAddress();
        }
        String status = getString(R.string.bt_connected_status, name);
        updateTxtInfo(status);
    }

    private void onBluetoothDisconnected(BluetoothDevice device) {

        setBtnPassVisibility(View.INVISIBLE);
        bluetoothBondManager.removeBond(device);

        String name = device.getName();
        if (TextUtils.isEmpty(name)) {
            name = device.getAddress();
        }
        String status = getString(R.string.bt_disconnected_status, name);
        updateTxtInfo(status);
    }


    private void updateTxtInfo(String info) {
        getHandler().obtainMessage(MSG_UPDATE_TXT_INFO, info).sendToTarget();

    }

    private void doUpdateTxtInfo(String info) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(txtInfo.getText())) {
            String txt = txtInfo.getText().toString();
            if (txt.length() < 1024 * 3) {
                sb.append(txtInfo.getText());
                sb.append("\n");
            }
        }
        sb.append(info);

        txtInfo.setText(sb.toString());

    }

    ////////////////////////////////////////////////
    ////////////////////////////////////////////////

    private final static int MSG_UPDATE_TXT_INFO = 2000;

    private final static int MSG_SET_BTNPASS_VISIBLE = 2001;
    private final static int DELAY_SET_BTNPASS_VISIBLE = 5000;//5s


    @Override
    protected void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_UPDATE_TXT_INFO:
                if (msg.obj instanceof String) {
                    doUpdateTxtInfo((String) msg.obj);
                }
                break;
            case MSG_SET_BTNPASS_VISIBLE:
                setBtnPassVisibility(View.VISIBLE);
                break;

        }
    }

}
